package com.wchat.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wchat.bean.entity.Users;
import com.wchat.bean.vo.UserVo;
import com.wchat.config.GlobalKey;
import com.wchat.mapper.UsersMapper;
import com.wchat.service.UserService;
import com.wchat.utils.JwtUtil;
import com.wchat.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author : willian fu
 * @date : 2021/8/30
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    private static final String SALT = "*&#!wchat..";

    @Override
    public Object login(String username, String password) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        if (Validator.isMobile(username)) {
            wrapper.eq("mobile", username);
        } else {
            wrapper.eq("user_name", username);
        }
        wrapper.eq("psw", DigestUtil.md5Hex16(password + SALT));
        Users users = usersMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(users)) {
            return R.badRequest("用户名或密码错误");
        } else {
            String tk = jwtUtil.jwtGetToken(users);
            redisTemplate.opsForHash().put(GlobalKey.TOKEN_KEY, users.getUserId().toString(), tk);
            return R.ok(UserVo.builder().userId(users.getUserId())
                    .userName(users.getUserName())
                    .sex(users.getSex())
                    .avatar(users.getAvatar())
                    .nick(users.getNick())
                    .token(tk)
                    .build());
        }
    }

    @Override
    public Object userRegister(String mobile, String username, String avatar, String password) {
        if (Validator.isMobile(mobile)) {
            if (!Validator.isGeneral(mobile, 5, 20)) {
                return R.badRequest("只能为长度5~20的字母数字下划线组成");
            }
            try {
                Users build = Users.builder().userName(username).mobile(mobile)
                        .nick(username)
                        .avatar(avatar).psw(DigestUtil.md5Hex16(password + SALT))
                        .build();
                usersMapper.insert(build);
                return R.ok("注册成功");
            } catch (Exception e) {
                return R.badRequest("用户名/手机号已被注册，请更换");
            }
        } else {
            return R.badRequest("请输入正确的手机号");
        }
    }

    @Override
    public Object updateInfo(Users user) {
        try {
            usersMapper.updateById(Users.builder()
                    .userId(user.getUserId())
                    .nick(user.getNick())
                    .sex(user.getSex())
                    .sign(user.getSign())
                    .avatar(user.getAvatar())
                    .wx(user.getWx())
                    .qq(user.getQq())
                    .build());
            return R.ok("修改成功");
        } catch (Exception e) {
            return R.badRequest("修改信息失败");
        }
    }

    @Override
    public Object getUserInfoById(Integer userId) {
        return usersMapper.selectOne(new QueryWrapper<Users>()
                .select("user_id", "user_name", "nick", "avatar", "sex")
                .eq("user_id", userId));
    }

    @Override
    public Object updatePassword(String oldPsw, String newPsw) {
        Integer userId = jwtUtil.jwtGetUser().getUserId();
        Users users = usersMapper.selectById(userId);
        if (users.getPsw().equals(DigestUtil.md5Hex16(oldPsw + SALT))) {
            usersMapper.updateById(Users.builder().userId(userId)
                    .psw(DigestUtil.md5Hex16(newPsw + SALT)).build());
            return R.ok("修改成功");
        }
        return R.badRequest("密码不匹配");
    }
}
